package com.example.gss.controller;

import com.example.gss.entity.Student;
import com.example.gss.entity.Tutor;
import com.example.gss.Service.StudentService;
import com.example.gss.Service.TutorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private StudentService studentService;
    
    @Autowired
    private TutorService tutorService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        String role = loginData.get("role");
        
        if ("student".equals(role)) {
            // 学生登录
            Optional<Student> studentOpt = studentService.findByStudentIdAndPassword(username, password);
            if (studentOpt.isPresent()) {
                Student student = studentOpt.get();
                Map<String, Object> result = new HashMap<>();
                result.put("role", "student");
                result.put("studentId", username);
                result.put("name", student.getName());
                result.put("grade", student.getGrade());
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("学号或密码错误");
            }
        } else if ("professor".equals(role)) {
            // 导师登录
            Optional<Tutor> tutorOpt = tutorService.findByTutorIdAndPassword(username, password);
            if (tutorOpt.isPresent()) {
                Tutor tutor = tutorOpt.get();
                Map<String, Object> result = new HashMap<>();
                result.put("role", "professor");
                result.put("tutorId", username);
                result.put("name", tutor.getName());
                result.put("title", tutor.getTitle());
                result.put("department", tutor.getDepartment());
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("工号或密码错误");
            }
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无效的用户类型");
        }
    }
} 